package java_concurrency_program_design_in_practice.stop_suspend_resume;

import java.util.concurrent.locks.LockSupport;

/**
 * LockSupport和Thread.suspend()相比，它弥补了由resume()在前发生，导致线程无法继续执行的情况<br/>
 * 和Object.wait()相比，他不需要先获得某个对象的锁，也不会抛出InterruptException<br/>
 * <br/>
 * LockSupport类使用类似信号量的机制，它为每一个线程准备了一个许可，<br/>
 * 如果许可可用，那么park()函数会立即返回，并且消费这个许可，如果许可不可用，就会阻塞<br/>
 * 而unpark()则使得一个许可变为可用，这一点使得：
 * 即使unpark()发生在park()之前，他也可以使得下一次的park()操作立即返回
 *
 * @author lixiangke
 * @date 2017/12/8
 */
public class LockSupportTest {
    public static Object u = new Object();
    static ChangeObjectThread t1 = new ChangeObjectThread("t1");
    static ChangeObjectThread t2 = new ChangeObjectThread("t2");

    public static class ChangeObjectThread extends Thread {
        public ChangeObjectThread(String name) {
            super.setName(name);
        }

        @Override
        public void run() {
            synchronized (u) {
                System.out.println("in " + getName());
                LockSupport.park();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        t1.start();
        Thread.sleep(100);
        t2.start();
        LockSupport.unpark(t1);
        LockSupport.unpark(t2);
        t1.join();
        System.out.println("t1 Over");
        t2.join();
        System.out.println("t2 Over");
    }
}
